import React, {Component} from 'react';
import {Layout, Menu, message, Breadcrumb, Icon} from 'antd';
import connect from "react-redux/es/connect/connect";
import { Route, Switch, withRouter} from 'react-router-dom';
import ajax from '../../util/AjaxUtil';
import qs from 'qs';
import {getValue} from '../../util/StorageUtil';
import './index.less';
import {update_user_info, update_menu_item, show_component, action_re_login} from '../../util/Constant';
import axios from 'axios';
import 'font-awesome/css/font-awesome.css';
import ComponentUtil from "../../util/ComponentUtil";
import IndexHeader from '../header/Header';

const {Header, Content, Sider} = Layout;

class Index extends Component {
    render() {
        let {menuItem} = this.props;
        return (
            <Layout style={{height: '100vh'}}>
                <Sider
                    breakpoint="xs"
                    collapsed={this.props.collapsed}
                    onCollapse={(collapsed, type) => {
                        console.log("sad")
                    }}
                >
                    <div className="logo"/>
                    <Menu theme="dark" mode="inline" defaultSelectedKeys={['1']}>
                        {
                            menuItem == null ? null :
                                menuItem.children[0].children.map(this.eachData.bind(this))
                        }
                    </Menu>
                </Sider>
                <Layout>
                    <Header className={"index-header"} id={'indexHeaderBar'}>
                        <IndexHeader/>
                    </Header>
                    <Content className={"index-content"}>
                            <div className="content-div">
                                <Switch>
                                    {
                                        ComponentUtil.getAllComponentRoutes().map(route => (
                                            <Route key={route.path} path={route.path} component={ComponentUtil.loadComponent(route.component)}  exact={route.exact} />
                                        ))
                                    }
                                </Switch>
                            </div>
                    </Content>
                </Layout>
            </Layout>
        );
    }

    /**
     * 递归生成menu的item
     * @param item
     * @param key
     * @param map
     * @returns {*}
     */
    eachData(item, key, map) {
        if (item.type !== 1) {  //1表示资源,没有可显示的内容
            if (item.children && item.children.length > 0) {
                return (
                    <Menu.SubMenu
                        key={item.id}
                        title={
                            <React.Fragment>
                                <Icon type={item.icon} />
                                <span>{item.name}</span>
                            </React.Fragment>
                        }
                    >
                        {item.children.map(this.eachData.bind(this))}
                    </Menu.SubMenu>
                )
            } else {
                return (
                    <Menu.Item key={item.id}
                               onClick={this.props.menuItemClick.bind(this)}
                               componentname={item.component}>
                        <Icon type={item.icon} />
                        <span>{item.name}</span>
                    </Menu.Item>
                )
            }
        }
    }

    componentDidMount() {
        let instance = this;
        axios.all([this.props.getUser()])
            .then(axios.spread(function () {
                if (instance.props.userInfo && instance.props.userInfo.id){
                    // 获取用户信息的请求执行完成
                    //获取用户有权限查看的菜单
                    instance.props.getMenuByUser(instance.props.userInfo.id);
                } else {
                    instance.props.toLogin();
                }
            }));

    }

    findMenuPath(menuKey) {
        let names = [];
        this.props.menuItem.children[0].children.map((item, key, map) => {
            this.eachDataName(item, menuKey, names);
            return item;
        });

        let menuNames = [];
        //将数组倒序
        for (let i = names.length - 1; i >= 0; i--) {
            menuNames.push(names[i]);
        }

        return menuNames;
    }

    eachDataName(item, menuKey, names) {
        if (item.id === menuKey) {
            names.push(item.name);
            return true;
        } else {
            if (item.children) {
                let hasKey = false;
                item.children.map((itemChild, key, map) => {
                    let tmp = this.eachDataName(itemChild, menuKey, names);
                    if (tmp === true) {
                        hasKey = tmp;
                    }
                    return itemChild;
                });
                if (hasKey) {
                    names.push(item.name);
                }
                return hasKey;
            } else {
                return false;
            }
        }
    }
}

const mapStateToProps = (state) => {
    return {
        isLogin: state.isLogin,
        username: state.username,
        userInfo: state.userInfo,
        menuItem: state.menuItem,
        showComponent: state.showComponent,
        showComponentPath: state.showComponentPath,
        collapsed: state.collapsed
    }
};

const mapDispatchToProps = (dispatch) => {
    return {
        getUser() {
            //获取用户信息
            return ajax.post('/userCenter/user/findUserInfoByUsername',
                qs.stringify({username: getValue("username")}))
                .then((response) => {
                    dispatch({
                        type: update_user_info,
                        userInfo: response.data
                    });
                })
                .catch((error) => {
                    message.error('获取用户信息失败');
                    console.log(error);
                });
        },
        getMenuByUser(userId) {
            ajax.post('/userCenter/menu/findMenuByUserId',
                qs.stringify({userId: userId}))
                .then((resource) => {
                    if (resource.data) {
                        dispatch({
                            type: update_menu_item,
                            menuItem: resource.data
                        });
                    }
                })
                .catch((error) => {
                    message.error('获取菜单数据失败')
                });
        },
        menuItemClick(e) {
            //查找被点击菜单和父菜单的名字
            let key = parseInt(e.key);
            let menuPath = this.findMenuPath(key);

            dispatch({
                type: show_component,
                showComponent: null,
                showComponentPath: menuPath
            });
            if (e.item.props.componentname==null || e.item.props.componentname===''){
                this.props.history.push('/');
            } else {
                this.props.history.push(e.item.props.componentname);
            }
        },
        toLogin(){
            dispatch({
                type:action_re_login,
                isLogin:false
            });
        }
    }
};

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Index));
